// use async
var path = require('path');
var async = require('async');
var fs = require('fs')

module.exports = function(dir, cb) {
	function readdir(next) {
		fs.readdir(dir, next);
	}

	function stat(files, next) {
		var paths = files.map(function(file) {
			return path.join(dir, file)
		});

		async.map(paths, fs.stat, function(err, stats) {
			next(err, files, stats);
		});
	}

	function size(files, stats, next) {
		var nFiles = stats.filter(function(stat) {
			return stat.isFile();
		});
		var largest = nFiles.reduce(function(pre, next) {
			var pSize = pre.size;
			var nSize = next.size;
			return pSize > nSize ? pre : next;
		});
		return next(null, files[stats.indexOf(largest)]);
	}

	async.waterfall([readdir, stat, size], cb);
}